package com.stox.client.ui.javafx.widget;

import javafx.event.EventHandler;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;

import com.stox.client.ui.core.event.EventPublisher;
import com.stox.client.ui.core.event.ScripSelectionEvent;
import com.stox.client.ui.core.model.intf.HasNavigable;
import com.stox.client.ui.core.model.intf.Navigable;
import com.stox.client.ui.javafx.core.ScripDragEventHandler;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;
import com.stox.shared.core.model.intf.HasScrip;

public abstract class AbstractHasScripListView<T extends HasScrip> extends
		ListView<T>  implements HasNavigable<T>{

	private final Class<T> hasScripType;
	
	public AbstractHasScripListView(Class<T> hasScripType) {
		this.hasScripType = hasScripType;
		getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
		
		setCellFactory(new javafx.util.Callback<ListView<T>, ListCell<T>>(){
			@Override
			public ListCell<T> call(ListView<T> listView) {
				return new ListCell<T>(){
					@Override
					protected void updateItem(T item, boolean empty) {
						super.updateItem(item, empty);
						UI.style(this, CSS.scripCell);
						if(!empty && null != item){
							setText(item.getScrip().getName().trim());
						}else{
							setText(null);
						}
					}
				};
			}
		});
		VBox.setVgrow(this, Priority.ALWAYS);
		
		setOnDragDetected(new ScripDragEventHandler());
		addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>(){
			@Override
			public void handle(MouseEvent event) {
				if(MouseButton.PRIMARY.equals(event.getButton()) && 2 == event.getClickCount()){
					publishEvent();
				}
			}
		});
		addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>(){
			@Override
			public void handle(KeyEvent event) {
				if(KeyCode.ENTER.equals(event.getCode())){
					publishEvent();
				}
			}
		});
	}
	
	@Override
	public Navigable<T> getNavigable() {
		return new ListViewNavigableDecorator<>(this, hasScripType);
	}
	
	public void publishEvent(){
		EventPublisher.publishEvent(new ScripSelectionEvent(this, getNavigable()));
	}
}
